﻿using Moven.Data;
using Moven.ViewModels;
using Moven.Controls;
using System.Collections.Generic;
using System.Linq;
using static Moven.ViewModels.ArticleWithBookmark;
using Xamarin.Forms;

namespace Moven.Views
{
	public partial class ArticlesPage
    {
	  	public bool IsAllArticlesPage => MenuType == MenuType.AllArticles;
		public bool IsBookmarksPage => MenuType == MenuType.Bookmarks;
		public bool IsTagsPage => MenuType == MenuType.Tags;

		public MenuType MenuType { get; set; }

		public ArticlesViewModel ViewModel => BindingContext as ArticlesViewModel;

		public string Tag
		{
			get { return ViewModel.Tag; }
			set { ViewModel.Tag = value; }
		}

        public ArticlesPage(string title, 
            IEnumerable<Article> articles, 
            MenuType menuType) :
            this(title, articles.Select(FromArticle).ToList(), menuType)
        { }

        public ArticlesPage(string title, 
            List<ArticleWithBookmark> articles,
            MenuType menuType)
        {
			InitializeComponent();
			MenuType = menuType;
			var vm = new ArticlesViewModel(title, MenuType, articles)
			{
				Navigation = Navigation,
				ArticlesList = listView
			};
			BindingContext = vm;

			if (vm.CanRefresh)
            {
				var refreshButton = new ExtendedToolbarItem(ToolbarItems)
                {
                    Icon = "refresh.png",
                    Command = vm.RefreshArticlesCommand,
                    Text = "刷新墨文"
                };
				var searchButton = new ExtendedToolbarItem(ToolbarItems)
				{
					Icon = "search.png",
					Text = "搜索",
					Command = new Command(async () => await Navigation.PushAsync(new SearchPage(ViewModel.AllArticles.ToList())))
				};
            }

            Statics.ArticlesStore.ArticlesRefreshed += (_, result) =>
            {
				if (result.Status == RefreshArticlesStatus.Failure)
				{
					return;
				}
				var newArticles = result.NewArticles;
				if (newArticles.IsNullOrEmpty())
				{
					return;
				}
				var articlesToBeAdded = newArticles.OrderBy(x => x.Index).
						 Select(FromArticle).
						 Where(article => IsAllArticlesPage ||
										 (menuType == MenuType.ArticlesOfTag && article.Tags.Contains(Tag))
							  );

				foreach (var article in articlesToBeAdded)
                {
					article.IsNew = true;
					Articles.Insert(0, article);
					ViewModel.AllArticles.Insert(0, article);
                }
				if (articlesToBeAdded.Any() && IsAndroid)
				{
					listView.ScrollTo(Articles.First(), ScrollToPosition.Start, true);
				}
				UpdateUI();
            };
			UpdateUI();
        }
    }
}
